import { _decorator, Component, Collider2D, Contact2DType, IPhysics2DContact, Node, Vec3 } from 'cc';
import { Card } from './Card';
const { ccclass, property } = _decorator;

@ccclass('TableauPile')
export class TableauPile extends Component {
    @property(Card)
    public topCard: Card | null = null;
    @property(Card)
    public bottomCard: Card | null = null;
    onLoad() {

    }
    protected start(): void {

    }


    getCardCount(): number {
        return this.node.children.length;
    }


    canDropCard(cardComp: Card): boolean {
        const topCard = this.topCard;
        if (topCard == null) {
            return true;
        }
        return topCard.suit === cardComp.suit && topCard.rank === cardComp.rank + 1;
    }

    public addCard(cardComp: Card) {
        const topCard = this.topCard;

        let preTableauPile = cardComp.tableauPile;
        if (preTableauPile != null && preTableauPile.bottomCard != null && preTableauPile.bottomCard == cardComp) {
            preTableauPile.bottomCard = null;
        }
        if (preTableauPile) {
            preTableauPile.topCard = cardComp.preCard;
        }

        if (topCard != null) {
            this.topCard.setNextCard(cardComp);
            cardComp.setPreCard(this.topCard);
            this.topCard = cardComp;
        } else {
            this.topCard = cardComp;
            this.bottomCard = cardComp; 
            if (cardComp.preCard != null) {
                cardComp.preCard.setNextCard(null);
            }
            cardComp.setPreCard(null);
        }
        let card = cardComp;
        do {
            const yOffset = -this.node.children.length * 35;
            this.node.insertChild(card.node, this.node.children.length);
            card.node.setPosition(new Vec3(0, yOffset, 0));
            card.tableauPile = this;

            // card.moveTo(new Vec3(0, yOffset, 0), 0, () => {
            // });
            if (card.nextCard === null) {
                break;
            }
            card = card.nextCard;
        } while (card != null);
    }


    // 移除顶部卡牌
    public removeTopCard(): Node | null {
        if (this.node.children.length === 0) return null;
        const card = this.node.children[this.node.children.length - 1];
        this.node.removeChild(card);
        return card;
    }




}
